<template>
	<div class="ll-page">
		<!-- S 查询 -->
		<div class="ll-page-query flex justify-between">
			<n-form
				inline
				:model="model"
				label-placement="left"
				:show-feedback="false"
				class="flex-1 flex-wrap"
			>
				<n-form-item label="上传时间：" path="uploadTime">
					<n-date-picker
						v-model:value="model.uploadTime"
						type="daterange"
						format="yyyy-MM-dd"
						clearable
						@update:value="listTableData"
					/>
				</n-form-item>
				<n-form-item label="状态：" path="status">
					<n-select
						v-model:value="model.status"
						:options="statusOptions"
						class="w-193px"
						@update:value="listTableData"
					/>
				</n-form-item>
			</n-form>
			<n-button color="rgba(0, 0, 0, 0.1)" text-color="#333333" @click="reset">重置</n-button>
			<n-button type="primary" style="margin-left: 10px" @click="showAdd.flag = true">
				新增Banner
			</n-button>
		</div>
		<!-- E 查询 -->

		<!-- S 表格 -->
		<div class="ll-page-table">
			<n-data-table
				:columns="columns"
				:data="tableData"
				:pagination="paginationReactive"
				:scroll-x="1400"
				:remote="true"
				flex-height
				:style="{ height: '100%' }"
			/>
		</div>
		<!-- E 表格 -->
		<n-modal
			v-model:show="showDisabled.flag"
			preset="dialog"
			:title="showDisabled.title"
			:content="showDisabled.content"
			:show-icon="false"
			negative-text="取消"
			positive-text="确定"
			@positive-click="sureShowDisabled"
		/>
		<n-modal
			v-model:show="showDetail.flag"
			title="详情"
			preset="dialog"
			:show-icon="false"
			:mask-closable="false"
			style="width: 500px; padding-bottom: 12px; border-radius: 12px"
		>
			<div class="ll-modal-body">
				<div class="ll-list-item" style="padding-top: 20px; margin-bottom: 40px">
					<span class="ll-list-item-title">所属页面：</span>
					<span>{{ clickRowData.positionTypeStr }}</span>
				</div>
				<div class="ll-list-item" style="height: 80px; margin-bottom: 0">
					<span class="ll-list-item-title">图片：</span>
					<div style="width: 120px; height: 80px; text-align: center">
						<n-image :src="clickRowData.mediaUrl" />
					</div>
				</div>
				<div class="ll-list-item">
					<span class="ll-list-item-title">产品链接：</span>
					<span>{{ clickRowData.linkUrl }}</span>
				</div>
			</div>
			<div
				style="
					position: absolute;
					width: 500px;
					height: 1px;
					left: -28px;
					top: 210px;
					box-shadow: 0px 2px 2px 0px rgba(0, 0, 0, 0.02), 0px -1px 0px 0px #f5f5f5;
				"
			></div>
			<template #action>
				<n-button
					style="border-radius: 4px; border: none; margin-top: 20px"
					color="rgba(0, 0, 0, 0.1)"
					text-color="#333333"
					@click="showDetail.flag = false"
				>
					关闭
				</n-button>
			</template>
		</n-modal>
		<n-modal
			v-model:show="showAdd.flag"
			title="新增Banner"
			preset="dialog"
			:show-icon="false"
			:mask-closable="false"
			style="width: 540px; padding-bottom: 12px; border-radius: 12px"
			class="my-item"
			@close="closeModal"
		>
			<div class="ll-modal-body" style="padding-top: 20px">
				<div class="ll-list-item">
					<span class="ll-list-item-title" style="width: 70px">所属页面：</span>
					<n-radio-group
						v-model:value="saveBannerDto.positionType"
						name="positionType"
						@change="changePositionType"
					>
						<n-space>
							<n-radio value="1">首页</n-radio>
							<n-radio value="2">素材圈</n-radio>
						</n-space>
					</n-radio-group>
				</div>
				<div class="ll-list-item" style="height: 65px; padding-top: 20px">
					<span class="ll-list-item-title">上传图片：</span>
					<n-upload
						:action="`${baseConfig.BASE_URL}/anchor/platform/anchors/common/upload`"
						list-type="image-card"
						:default-file-list="fileListD"
						accept=".png,.jpg"
						:headers="headers"
						style="z-index: 998"
						@finish="onFinishUpload"
						@before-upload="onbeforeUpload"
					>
						<div style="width: 120px; height: 80px; text-align: center">
							<img
								src="~@/assets/images/icon_up_img@2x.png"
								style="width: 24px; height: 24px; margin: 20px 0 0 46px"
							/>
							<span
								style="
									font-size: 12px;
									font-family: PingFangSC-Regular, PingFang SC;
									font-weight: 400;
									color: #333333;
								"
							>
								点击上传
							</span>
						</div>
					</n-upload>
				</div>
				<div
					style="
						position: absolute;
						top: 60px;
						left: 190px;
						width: 150px;
						height: 95px;
						z-index: 999;
						background-color: white;
					"
				></div>
				<div class="ll-list-item middle-title">
					<span class="ll-list-item-title"></span>
					<img src="~@/assets/images/icon_tdzx_zy@2x.png" />
					<div class="tip-img-desc">仅支持上传一张png、jpg格式，尺寸1065*492</div>
				</div>
				<div class="ll-list-item">
					<span class="ll-list-item-title" style="width: 85px">产品链接：</span>
					<n-input-group>
						<n-input-group-label>{{ pageAddr }}</n-input-group-label>
						<n-input
							v-model:value="saveBannerDto.linkUrl"
							aria-required="true"
							type="text"
							placeholder="产品ID"
							style="width: 80px"
						/>
					</n-input-group>
				</div>
			</div>
			<div
				style="
					position: absolute;
					width: 510px;
					height: 1px;
					left: -28px;
					top: 260px;
					box-shadow: 0px 2px 2px 0px rgba(0, 0, 0, 0.02), 0px -1px 0px 0px #f5f5f5;
				"
			></div>
			<template #action>
				<n-button
					style="border-radius: 4px; border: none; margin-top: 20px"
					color="rgba(0, 0, 0, 0.1)"
					text-color="#333333"
					@click="closeModal"
				>
					取消
				</n-button>
				<n-button
					type="primary"
					style="border-radius: 4px; border: none; margin-top: 20px"
					@click="saveBanner"
				>
					确定
				</n-button>
			</template>
		</n-modal>
	</div>
</template>

<script setup>
import { h, reactive, ref } from 'vue';
import { NButton, useMessage, NImage } from 'naive-ui';
import { findByPage, save, showOrDisabled, upload } from '../../api/banner';
import dayjs from 'dayjs';
import baseConfig from '@/config';
import { getQueryParam } from '@/utils/index';

const message = useMessage();
const headers = {
	Authorization: getQueryParam('token') ? getQueryParam('token') : baseConfig.LL_APP_TOKEN
};

// ------------------------------------------------ S 常量定义 ------------------------------------------------
const statusOptions = [
	{ label: '已隐藏', value: '0' },
	{ label: '已显示', value: '1' },
	{ label: '活动已结束', value: '2' },
	{ label: '已满员', value: '3' }
];
const model = reactive({
	uploadTime: null,
	status: null
});

const paginationReactive = reactive({
	pageCount: 1,
	page: 1,
	pageSize: 10,
	showSizePicker: true,
	pageSizes: [10, 20, 50],
	itemCount: 0,
	prefix({ itemCount }) {
		return `共${itemCount}条`;
	},
	onChange: (page) => {
		paginationReactive.page = page;
		listTableData();
	},
	onPageSizeChange: (pageSize) => {
		paginationReactive.pageSize = pageSize;
		paginationReactive.page = 1;
		listTableData();
	}
});
const columns = [
	{
		title: '上传时间',
		key: 'createTime'
	},
	{
		title: '所属页面',
		key: 'positionTypeStr'
	},
	{
		title: '图片',
		key: 'mediaUrl',
		render(row) {
			return h(NImage, { width: '80', height: '50', src: row.mediaUrl });
		}
	},
	{
		title: '链接',
		key: 'linkUrl'
	},
	{
		title: '操作人',
		key: 'createUserNickName'
	},
	{
		title: '状态',
		key: 'statusStr'
	},
	{
		title: '操作',
		key: 'actions',
		width: 200,
		render(row) {
			return [
				h(
					NButton,
					{
						size: 'small',
						text: true,
						type: 'primary',
						style: {
							marginRight: row.status === 0 || row.status === 1 ? '8px' : 0,
							fontSize: '14px'
						},
						onClick: () => isShow(row)
					},
					{
						default: () => {
							if (row.status === 0) {
								return '显示';
							} else if (row.status === 1) {
								return '隐藏';
							}
						}
					}
				),
				h(
					NButton,
					{
						size: 'small',
						text: true,
						type: 'primary',
						style: {
							marginRight: '8px',
							fontSize: '14px'
						},
						onClick: () => detail(row)
					},
					{ default: () => '详情' }
				)
			];
		}
	}
];
let tableData = ref([]);
let pageAddr = ref('/tandianPage/ProductDetail?productId=');

let showDisabled = ref({
	flag: false,
	title: '',
	Content: ''
});
let showDetail = ref({
	flag: false
});
let showAdd = ref({
	flag: false
});
let clickRowData = ref({});

let saveBannerDto = reactive({
	mediaUrl: '',
	linkUrl: '',
	positionType: null
});
let fileListD = ref([]);
// ------------------------------------------------ E 常量定义 ------------------------------------------------
// ------------------------------------------------ S 函数定义 ------------------------------------------------
const reset = () => {
	model.uploadTime = null;
	model.status = null;
	listTableData();
};
const changePositionType = () => {
	if (saveBannerDto.positionType === '1') {
		pageAddr.value = '/tandianPage/ProductDetail?productId=';
	} else if (saveBannerDto.positionType === '2') {
		pageAddr.value = '/materialPage/MaterialDownload?productId=';
	}
};
const listTableData = () => {
	const params = {
		startDate: model.uploadTime != null ? dayjs(model.uploadTime[0]).format('YYYY-MM-DD') : null,
		endDate: model.uploadTime != null ? dayjs(model.uploadTime[1]).format('YYYY-MM-DD') : null,
		status: model.status,
		pageIndex: paginationReactive.page,
		pageSize: paginationReactive.pageSize
	};
	console.log(params);
	findByPage(params).then((res) => {
		tableData.value = res.data.records;
		paginationReactive.pageCount = res.data.pages;
		paginationReactive.itemCount = res.data.total;
	});
};
const isShow = (rowData) => {
	if (rowData.status === 0) {
		showDisabled.value.title = '显示';
		showDisabled.value.content = '显示后Banner图在C端显示，创作者和探店主播将会看见，是否确认显示';
	} else if (rowData.status === 1) {
		showDisabled.value.title = '隐藏';
		showDisabled.value.content =
			'隐藏后Banner图不在C端显示，创作者和探店主播将不会看见，是否确认隐藏';
	}
	clickRowData.value = rowData;
	showDisabled.value.flag = true;
};
const detail = (rowData) => {
	clickRowData.value = rowData;
	showDetail.value.flag = true;
};
const sureShowDisabled = () => {
	const params = {
		id: clickRowData.value.id
	};
	showOrDisabled(params).then((res) => {
		listTableData();
		if (res.data) {
			message.success('操作成功');
		} else {
			message.error('操作失败');
		}
	});
};

const closeModal = () => {
	showAdd.value.flag = false;
	fileListD.value = [];
	saveBannerDto.linkUrl = null;
	saveBannerDto.mediaUrl = null;
	saveBannerDto.positionType = null;
};

const saveBanner = () => {
	const params = {
		mediaUrl: saveBannerDto.mediaUrl,
		linkUrl: pageAddr.value + saveBannerDto.linkUrl,
		positionType: saveBannerDto.positionType
	};
	if (!params.positionType) {
		message.warning('请选择所属页面');
		return;
	}
	if (!params.mediaUrl) {
		message.warning('图片必须上传一张');
		return;
	}
	if (!saveBannerDto.linkUrl) {
		message.warning('产品ID不能为空');
		return;
	}
	save(params).then((res) => {
		if (res.code === 200) {
			listTableData();
			message.success('操作成功');
			closeModal();
		} else {
			showAdd.value.flag = true;
			message.error(res.message);
		}
	});
};

const onFinishUpload = ({ file, event }) => {
	let item = {
		id: file.id,
		name: file.name,
		status: file.status,
		url: JSON.parse(event.target.response).data
	};
	fileListD.value.push(item);
	saveBannerDto.mediaUrl = JSON.parse(event.target.response).data;
};

const onbeforeUpload = async ({ file, fileList }) => {
	const f = file.file;
	const flag = await imgPx(f);
	console.log(123, flag);
	if (!flag) {
		message.warning('只能上传1065*492的图片');
		return false;
	}
	if (fileList.length === 1) {
		message.warning('只能上传一张图片');
		return false;
	}
	return true;
};

const imgPx = async (f) => {
	return new Promise((resolve) => {
		const reader = new FileReader();
		reader.onload = (e) => {
			const data = e.target.result;
			//加载图片获取图片真实宽度和高度
			const image = new Image();
			image.onload = () => {
				const width = image.width;
				const height = image.height;
				resolve(width === 1065 && height === 492);
			};
			image.src = data;
		};
		reader.readAsDataURL(f);
	});
};

// ------------------------------------------------ E 函数定义 ------------------------------------------------
// ------------------------------------------------ S 函数调用 ------------------------------------------------
listTableData();
// ------------------------------------------------ E 函数调用 ------------------------------------------------
</script>

<style lang="less" scoped>
.ll-page {
	height: 100%;
	flex-direction: column;
	display: flex;
	background-color: #ffffff;
	&-query {
		background: @bg;
		padding: @padding-10;
		margin-right: 10px;
		margin-left: 10px;
		margin-top: 10px;
		border-radius: 3px;
		border: 1px solid #f0f0f0;
	}

	&-table {
		padding: 10px;
		overflow: hidden;
		flex: 1 1 0%;
	}
}
.ll-list-item {
	height: 34px;
	font-size: 14px;
	color: #333333;
	display: flex;
	align-items: center;
	margin-bottom: 16px;
	&-title {
		color: #666666;
		display: inline-block;
		width: 70px;
		text-align: right;
	}
}
.middle-title {
	img {
		width: 14px;
		height: 14px;
		float: left;
	}
}
.tip-img-desc {
	font-size: 12px;
	font-family: SFCompact-Regular, SFCompact;
	font-weight: 400;
	color: #f5894e;
	line-height: 16px;
	float: left;
}
::v-deep(.my-item .n-image img) {
	//height: 50px !important;
	width: 120px !important;
	height: 80px !important;
}

::v-deep(.n-upload .n-upload-file-list.n-upload-file-list--grid) {
	display: inline-block;
}
::v-deep(.n-upload-dragger) {
	background-color: #f0f0f0;
}
::v-deep(.n-upload-trigger.n-upload-trigger--image-card) {
	width: 120px;
	height: 80px;
}
::v-deep(.n-upload-file) {
	float: left;
	margin-right: 10px;
	width: 120px;
	height: 80px;
}
::v-deep(.n-upload .n-upload-file-list .n-upload-file.n-upload-file--image-card-type) {
	width: 120px;
	height: 80px;
}
::v-deep(.n-upload__trigger) {
	float: left;
	width: 120px;
	height: 80px;
}
::v-deep(.n-data-table-th) {
	background-color: #f5f5f5;
}
::v-deep(.n-dialog .n-dialog__action) {
	margin: -16px -28px -20px -28px;
	background-color: #666666 !important;
}
.ll-list-item-title {
	font-size: 14px;
	font-family: PingFangSC-Regular, PingFang SC;
	font-weight: 400;
	color: #333333;
}
</style>
